package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.lib.domain.CustomerCouponWallet;
import com.rockcent.mall.lib.domain.IntegrationCashCouponWallet;
import com.rockcent.mall.lib.domain.IntegrationCouponWallet;
import com.rockcent.mall.lib.domain.MerchantCoupon;
import com.rockcent.mall.lib.domain.enumclass.CustomerCouponWalletSource;
import com.rockcent.mall.lib.domain.enumclass.CustomerCouponWalletStatus;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.repository.CustomerCouponWalletRepository;
import com.rockcent.mall.lib.repository.MerchantCouponRepository;
import com.rockcent.service.IntegrationCashCouponWalletSrv;
import com.rockcent.service.IntegrationCouponWalletSrv;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangjh on 2016/12/14.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class CustomerCashCouponController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CustomerCashCouponController.class);

    @Autowired
    private IntegrationCashCouponWalletSrv integrationCashCouponWalletSrv;
    @Autowired
    private IntegrationCouponWalletSrv integrationCouponWalletSrv;

    @Autowired
    private CustomerHelper customerHelper;

    @Autowired
    private MerchantCouponRepository merchantCouponRepository;

    @Autowired
    private CustomerCouponWalletRepository customerCouponWalletRepository;


    /**
     * @api {get} /api/v2/customer/cash/coupon/page 可用现金券列表
     * @apiGroup integration
     * @apiVersion 1.0.0
     * @apiParam {String} userToken 用户Token
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiParam {Long} useNum <code> 0：未使用的现金券，1：已使用的现金券</code>  现金券状态
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":2,
     *                 "dateCreated":"2016-12-15 16:37:37",
     *                 "lastUpdated":"2016-12-15 16:38:49",
     *                 "version":1,
     *                 "cashCouponId":1,
     *                 "exchangeCode":"1001",
     *                 "exchangeNum":1,
     *                 "receiveNum":1,
     *                 "useNum":1,
     *                 "mallId":51,
     *                 "customerId":20,
     *                 "customerName":"aa",
     *                 "transactionId":"0002"
     *             }
     *         ],
     *         "totalCount":1,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10,
     *         "url":"/customer/coupon/page",
     *         "prevUrl":"/customer/coupon/page?pageNo=0&pageSize=10",
     *         "nextUrl":"/customer/coupon/page?pageNo=0&pageSize=10"
     *     }
     * }
     */
    @RequestMapping(value = Routes.CUSTOMER_CASH_COUPON_PAGE, method = RequestMethod.GET)
    public JsonResult customerCouponPage(HttpServletRequest request, Long useNum, Integer pageNo, Integer pageSize) {

        CustomerDto customerDto = customerHelper.getSession(request);

        RestDoing doing = jr -> {

            Long userId = customerDto.getId();
            PageResult<IntegrationCashCouponWallet> pageResult = integrationCashCouponWalletSrv.queryCashWalletList(useNum, userId, this.getPage(pageNo, pageSize));
            pageResult.setUrl(Routes.CUSTOMER_CASH_COUPON_PAGE);
            jr.data = pageResult;


        };
        return doing.go(request, log);

    }

    /**
     * @api {get} /api/v2/customer/cash/coupon/count 可用现金券数量
     * @apiGroup integration
     * @apiVersion 1.0.0
     * @apiParam {String} userToken 用户Token
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiParam {Long} useNum <code> 0：未使用的现金券，1：已使用的现金券</code>  现金券状态
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "unUsedTotal": 1,
     *      "usedTotal": 1
     * }
     * }
     */
    @RequestMapping(value = Routes.CUSTOMER_CASH_COUPON_COUNT, method = RequestMethod.GET)
    public JsonResult queryCashTotals(HttpServletRequest request) {

        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {

            Long userId = customerDto.getId();

            Long unUsedTotal = integrationCashCouponWalletSrv.queryCashWalletCount(0l, userId);
            Long usedTotal = integrationCashCouponWalletSrv.queryCashWalletCount(1l, userId);

            Map<String, Long> result = new HashMap<>();
            result.put("unUsedTotal", unUsedTotal == null ? 0 : unUsedTotal);
            result.put("usedTotal", usedTotal == null ? 0 : usedTotal);
            jr.data = result;

        };
        return doing.go(request, log);

    }


    /**
     * @api {post} /api/v2/customer/cash/coupon/receive 卡券领取
     * @apiGroup integration
     * @apiVersion 1.0.0
     * @apiParam {String} userToken 用户Token
     * @apiParam {Long} exchangeCode 兑换码
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.CUSTOMER_COUPON_RECEIVE, method = RequestMethod.POST)
    public JsonResult receiveIntergrationCoupon(HttpServletRequest request, @RequestBody IntegrationCashCouponWallet couponDto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        Long mallId = customerDto.getMallId();
//        log.info("======================>customerDto-->" + customerDto);

        RestDoing doing = jr -> {

            Long userId = customerDto.getId();
            String exchangeCode = couponDto.getExchangeCode();

            IntegrationCashCouponWallet integrationCashCouponWallet = integrationCashCouponWalletSrv.findByExchangeCodeAndExchangeNumAndReceiveNumAndUseNum(exchangeCode, 1L, 0L, 0L);
            IntegrationCouponWallet integrationCouponWallet = integrationCouponWalletSrv.findByExchangeCodeAndExchangeNumAndReceiveNumAndUseNum(exchangeCode, 1L, 0L, 0L);
            Map<String, String> result = new HashMap<>();
            Date now = new Date();
            if (null != integrationCashCouponWallet) {
                integrationCashCouponWallet.setReceiveNum(1l);
                integrationCashCouponWallet.setCustomerId(userId);
                integrationCashCouponWallet.setReceiveDate(now);
                IntegrationCashCouponWallet cashCouponWallet =integrationCashCouponWalletSrv.save(integrationCashCouponWallet);
                Long id = cashCouponWallet.getId();
                Long receiveNum = cashCouponWallet.getReceiveNum();
//                log.info("integrationCashCouponWallet id:{},receiveNum:{}",id,receiveNum);
                //现金券领取发消息
                try {
                    integrationCashCouponWalletSrv.findCashCouponWalletPushReceiveOverMsg(integrationCashCouponWallet.getMallId(),integrationCashCouponWallet.getCashCouponId());
                } catch (Exception e) {
//                    log.info("push receive over msg error");
                }

                result.put("type", "cash");
                jr.data = result;
            } else if (null != integrationCouponWallet) {

                MerchantCoupon coupon =  merchantCouponRepository.findByIdAndMallId(integrationCouponWallet.getCouponId(),mallId);
                if(coupon==null){
                    jr.remind("没有找到对应的积分卡券",log);
                    return;
                }

                Date dateDisabled = coupon.getDateDisabled();
                if (now.after(dateDisabled)){
                    jr.remind("相应的积分卡券过期",log);
                    return;
                }
                integrationCouponWallet.setReceiveNum(1l);
                integrationCouponWallet.setCustomerId(userId);
                integrationCouponWallet.setReceiveDate(now);
                integrationCouponWalletSrv.save(integrationCouponWallet);

                coupon.setLeaveTotal(coupon.getLeaveTotal()-1);
                merchantCouponRepository.save(coupon);


                CustomerCouponWallet couponWallet = new CustomerCouponWallet();
                couponWallet.setMerchantId(coupon.getMerchantId());
                couponWallet.setCouponId(integrationCouponWallet.getCouponId());
                couponWallet.setIntegrationCouponId(integrationCouponWallet.getId());
                couponWallet.setCustomerId(customerDto.getId());
                couponWallet.setMallId(mallId);
                couponWallet.setSource(CustomerCouponWalletSource.INTEGRATION);
                couponWallet.setStatus(CustomerCouponWalletStatus.TO_USE);
                couponWallet.setCustomerName(customerDto.getNickName());
                customerCouponWalletRepository.save(couponWallet);

                jr.data = "coupon";
                result.put("type", "coupon");
                jr.data = result;
            } else {
                jr.remind("输入的卡券兑换码不正确",log);
                return;
            }


        };
        return doing.go(request, log);


    }



    /**
     * @api {get} /api/v2/customer/cash/coupon/closeto/info 推荐现金券
     * @apiGroup integration
     * @apiVersion 1.0.0
     * @apiParam {String} userToken 用户Token
     * @apiParam {Integer} discountAmount 折扣后金额
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":3,
     *         "dateCreated":"2016-12-19 15:33:50",
     *         "lastUpdated":"2016-12-19 19:33:27",
     *         "version":2,
     *         "cashCouponId":1,
     *         "faceValue":40,
     *         "exchangeCode":"1003",
     *         "exchangeNum":1,
     *         "receiveNum":1,
     *         "useNum":0,
     *         "integrationChannelId":"1",
     *         "mallId":51,
     *         "customerId":20,
     *         "customerName":"aa",
     *         "transactionId":"0004"
     *     }
     * }
     */
    @RequestMapping(value = Routes.CUSTOMER_CASH_COUPON_CLOSETO_INFO, method = RequestMethod.GET)
    public JsonResult getCloseToCashCoupon(HttpServletRequest request, BigDecimal discountAmount) {

        CustomerDto customerDto = customerHelper.getSession(request);

        RestDoing doing = jr -> {

            Long userId = customerDto.getId();
            Long mallId = customerDto.getMallId();
            IntegrationCashCouponWallet integrationCashCouponWallet = integrationCashCouponWalletSrv.getCloseToCashCoupon(discountAmount,userId,mallId);
            log.info("======================>integrationCashCouponWallet:"+ integrationCashCouponWallet);
            jr.data = integrationCashCouponWallet;


        };
        return doing.go(request, log);

    }

}
